const httpRequest = require('../../utils/request');
const buildUrl = httpRequest.buildUrl || ((url) => url);

Page({
  data: {
    userRole: 'order_user',
    currentFilter: 'all',
    startDate: '',
    endDate: '',
    showFilterModal: false,

    // 筛选条件
    expressCompanies: [
      { name: '全部', value: '' },
      { name: '顺丰', value: '顺丰' },
      { name: '中通', value: '中通' },
      { name: '圆通', value: '圆通' },
      { name: '申通', value: '申通' },
      { name: '韵达', value: '韵达' },
      { name: '京东', value: '京东' },
      { name: '邮政', value: '邮政' }
    ],
    selectedCompany: '',
    minPrice: '',
    maxPrice: '',

    sortOptions: [
      { name: '最新发布', value: 'newest' },
      { name: '价格最高', value: 'price_desc' },
      { name: '价格最低', value: 'price_asc' },
      { name: '最近更新', value: 'recent' }
    ],
    selectedSort: 'newest',

    // 订单数据
    orders: [],
    filteredOrders: [],
    orderStats: {
      total: 0,
      completed: 0,
      pending: 0,
      amount: 0
    },

    // 分页
    page: 1,
    pageSize: 10,
    hasMore: true
  },

  onLoad(options) {
    const app = getApp();
    this.setData({
      userRole: app.globalData.userRole || 'order_user'
    });

    console.log('🧾 orderList 当前 userRole:', this.data.userRole);

    this.initDates();
    this.loadOrders();
  },

  onShow() {
    this.refreshOrders();
  },

  // 初始化日期
  initDates() {
    const today = new Date();
    const oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);

    this.setData({
      startDate: this.formatDate(oneWeekAgo),
      endDate: this.formatDate(today)
    });
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 加载订单
  async loadOrders() {
    const app = getApp();
    const userId = app.globalData.userId;

    if (!userId) {
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    try {
      const url = this.data.userRole === 'order_user'
        ? `/api/orders/user/${userId}`
        : `/api/orders/courier/${userId}`;

      const res = await this.request({
        url: url,
        method: 'GET',
        data: {
          page: this.data.page,
          pageSize: this.data.pageSize,
          startDate: this.data.startDate,
          endDate: this.data.endDate,
          status: this.data.currentFilter === 'all' ? '' : this.data.currentFilter,
          expressCompany: this.data.selectedCompany,
          minPrice: this.data.minPrice,
          maxPrice: this.data.maxPrice,
          sort: this.data.selectedSort
        }
      });

      if (res && res.success) {
        const raw = res.data;
        let list = [];

        if (Array.isArray(raw)) {
          list = raw;
        } else if (raw && Array.isArray(raw.orders)) {
          list = raw.orders;
        } else if (raw && Array.isArray(raw.list)) {
          list = raw.list;
        }

        const orders = list.map(order => ({
          ...order,
          statusText: this.getStatusText(order.status),
          createdAt: this.formatTime(order.created_at || order.createdAt),
          expectedTime: this.formatExpectedTime(order.expected_time || order.expectedTime),
          isRated: order.rating_id !== null && order.rating_id !== undefined
        }));

        console.log('📦 调试订单列表 status:', orders.map(o => ({ id: o.id, status: o.status })));

        if (this.data.page === 1) {
          this.setData({
            orders: orders,
            filteredOrders: this.filterOrders(orders, this.data.currentFilter)
          });
        } else {
          const merged = [...this.data.orders, ...orders];
          this.setData({
            orders: merged,
            filteredOrders: this.filterOrders(merged, this.data.currentFilter)
          });
        }

        // 后端 /user/:id 和 /courier/:id 当前不返回分页信息，这里做兼容处理
        this.setData({
          hasMore: (raw && typeof raw.hasMore === 'boolean') ? raw.hasMore : false,
          orderStats: raw && raw.stats ? raw.stats : this.data.orderStats
        });
      }
    } catch (error) {
      console.error('加载订单失败:', error);
      wx.showToast({ title: '订单加载失败', icon: 'none' });
    }
  },

  // 过滤订单
  filterOrders(orders, filter) {
    if (filter === 'all') return orders;

    const statusMap = {
      'pending': [1],      // 待接单
      'accepted': [2],     // 已接单
      'picked_up': [3],    // 已取件
      'delivering': [4],   // 送达中
      'completed': [5],    // 已完成
      'cancelled': [6]     // 已取消
    };

    return orders.filter(order =>
      statusMap[filter] && statusMap[filter].includes(order.status)
    );
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      1: '待接单',
      2: '已接单',
      3: '已取件',
      4: '送达中',
      5: '已完成',
      6: '已取消'
    };
    return statusMap[status] || '未知状态';
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (days === 0) {
      return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else if (days === 1) {
      return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else {
      return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    }
  },

  // 格式化期望时间
  formatExpectedTime(timeStr) {
    if (!timeStr) return '';
    return timeStr.split(' ')[1] || timeStr;
  },

  // 设置筛选
  setFilter(e) {
    const filter = e.currentTarget.dataset.filter;
    const filteredOrders = this.filterOrders(this.data.orders, filter);

    this.setData({
      currentFilter: filter,
      filteredOrders: filteredOrders
    });
  },

  // 日期变化
  onStartDateChange(e) {
    this.setData({ startDate: e.detail.value });
  },

  onEndDateChange(e) {
    this.setData({ endDate: e.detail.value });
  },

  // 搜索订单
  searchOrders() {
    this.setData({ page: 1 });
    this.loadOrders();
  },

  // 显示筛选模态框
  showFilterModal() {
    this.setData({ showFilterModal: true });
  },

  hideFilterModal() {
    this.setData({ showFilterModal: false });
  },

  // 选择快递公司
  selectCompany(e) {
    const company = e.currentTarget.dataset.company;
    this.setData({ selectedCompany: company });
  },

  // 价格输入
  onMinPriceInput(e) {
    this.setData({ minPrice: e.detail.value });
  },

  onMaxPriceInput(e) {
    this.setData({ maxPrice: e.detail.value });
  },

  // 选择排序
  selectSort(e) {
    const sort = e.currentTarget.dataset.sort;
    this.setData({ selectedSort: sort });
  },

  // 重置筛选
  resetFilters() {
    this.setData({
      selectedCompany: '',
      minPrice: '',
      maxPrice: '',
      selectedSort: 'newest'
    });
  },

  // 应用筛选
  applyFilters() {
    this.hideFilterModal();
    this.setData({ page: 1 });
    this.loadOrders();
  },

  // 查看订单详情
  viewOrderDetail(e) {
    const order = e.currentTarget.dataset.order;
    wx.navigateTo({
      url: `/pages/orderDetail/orderDetail?orderId=${order.id}&role=${this.data.userRole}`
    });
  },

  // 取消订单
  async cancelOrder(e) {
    const orderId = e.currentTarget.dataset.orderId;

    wx.showModal({
      title: '确认取消',
      content: '取消订单可能会影响您的信用分，确定要取消吗？',
      confirmColor: '#ff4d4f',
      success: async (res) => {
        if (res.confirm) {
          try {
            const result = await this.request({
              url: `/api/orders/${orderId}/cancel`,
              method: 'POST'
            });

            if (result.success) {
              wx.showToast({ title: '订单已取消' });
              this.refreshOrders();
            } else {
              wx.showToast({ title: result.message || '取消失败', icon: 'none' });
            }
          } catch (error) {
            wx.showToast({ title: '取消失败', icon: 'none' });
          }
        }
      }
    });
  },

  // 确认收货
  async confirmDelivery(e) {
    const orderId = e.currentTarget.dataset.orderId;

    wx.showModal({
      title: '确认送达并支付',
      content: '请确认已收到包裹，随后将前往支付本订单。',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: `/pages/payment/payment?orderId=${orderId}`
          });
        }
      }
    });
  },

  // 确认取件
  async confirmPickup(e) {
    const orderId = e.currentTarget.dataset.orderId;

    try {
      const result = await this.request({
        url: `/api/orders/${orderId}/pickup`,
        method: 'POST'
      });

      if (result.success) {
        wx.showToast({ title: '取件确认成功' });
        this.refreshOrders();
      } else {
        wx.showToast({ title: result.message || '操作失败', icon: 'none' });
      }
    } catch (error) {
      wx.showToast({ title: '操作失败', icon: 'none' });
    }
  },

  // 通知送达
  async notifyDelivery(e) {
    const orderId = e.currentTarget.dataset.orderId;

    try {
      const result = await this.request({
        url: `/api/orders/${orderId}/deliver`,
        method: 'POST'
      });

      if (result.success) {
        wx.showToast({ title: '已通知用户取件' });
        this.refreshOrders();
      } else {
        wx.showToast({ title: result.message || '操作失败', icon: 'none' });
      }
    } catch (error) {
      wx.showToast({ title: '操作失败', icon: 'none' });
    }
  },

  // 跳转到评价
  goToRating(e) {
    const orderId = e.currentTarget.dataset.orderId;
    wx.navigateTo({
      url: `/pages/rating/rating?orderId=${orderId}`
    });
  },

  // 跳转到发布订单
  goToCreateOrder() {
    wx.navigateTo({ url: '/pages/createOrder/createOrder' });
  },

  // 跳转到接单大厅
  goToOrderHall() {
    const app = getApp();
    app.switchRole('courier');
  },

  // 返回
  goBack() {
    wx.navigateBack();
  },

  // 加载更多
  loadMoreOrders() {
    if (!this.data.hasMore) return;

    this.setData({ page: this.data.page + 1 });
    this.loadOrders();
  },

  // 刷新订单
  refreshOrders() {
    this.setData({ page: 1 });
    this.loadOrders();
  },

  // 网络请求封装
  request(options) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: buildUrl(options.url || ''),
        method: options.method || 'GET',
        data: options.data,
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshOrders();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
});